import { agentService } from '../model/agent/service';
import { MonitorService } from './monitorService';
import { JobScheduleService } from './scheduler/scheduleService';
import { JobLifecycleManager } from './jobLifecycleManager';
import { configurationService } from './configService';
import { SimulationResultProcessor } from './jobResultProcessor';
import { SimluationDispatchService } from './dispatcher/dispatchService';
import { TypeORMService as DatabaseService } from './typeormService';
import { SimulationJobService } from '../model/simulation/service/index';
import { JobScanService } from './jobScanService';

export async function initServices() {

  // The database service must be initialized first, otherwise an error is reported:
  // EntityMetadataNotFoundError: No metadata for "Agent" was found.
  // Tips: Ensure that [typeorm.entities] are configured correctly in default.toml
  const databaseService = new DatabaseService();
  await databaseService.init();

  agentService.init();

  const monitorService = new MonitorService(agentService);
  monitorService.init();

  const schedulerScanInterval = configurationService.config.scheduler.scanInterval;
  const scheduleService = new JobScheduleService(new SimulationJobService(), agentService, schedulerScanInterval);
  scheduleService.init();

  const dispatcherScanInterval = configurationService.config.dispatcher.scanInterval;
  const dispatcherService = new SimluationDispatchService(new SimulationJobService(), dispatcherScanInterval);
  dispatcherService.init();

  const resultProcessor = new SimulationResultProcessor();

  const jobLifecycleManager = new JobLifecycleManager(scheduleService, dispatcherService, resultProcessor);
  jobLifecycleManager.init();

  const jobScanInterval = configurationService.config.simJob.scanInterval;
  const jobTimeout = configurationService.config.simJob.timeout;
  const jobScanService = new JobScanService(jobScanInterval, jobTimeout);
  jobScanService.init();
}